<?php
/**
 *   Joomdiet - administrator/components/controllers/filereceiver.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');

class JoomdietControllerFileReceiver extends JController
{
    function __construct() {
        // get requested view
        if(JRequest::getCmd('view') == '') {
            JRequest::setVar('view', 'default');
        }
        $this->item_type = 'Default';
        parent::__construct();
        
        $this->registerTask('addFood', 'editFood');
    }
    
    function processvarcsv()
    {
        $csvfile = JRequest::getVar('csvvariables', null, 'files', 'array');
        $message = "";
        
        // receiving file
        if (!is_array($csvfile))
            $message .= JText::_('COM_JOOMDIET_FILE_DOES_NOT_UPLOAD');
        
        if ($csvfile['error'] || ($csvfile['size'] < 1))
            $message .= ' '.JText::_('COM_JOOMDIET_FILE_DOES_NOT_EXIST');
        

        if (!JFile::upload($csvfile['tmp_name'], "/tmp".DS.$csvfile['name'])) {
            $message .= ' '.JText::_('COM_JOOMDIET_UPLOAD_FILE_ERROR');
        }
        
        $output_messages = array();
        $output_messages[] = JText::_('COM_JOOMDIET_CSV_FILE_UPLOADED');
        
        // process csv
        // try to open as csv
        if (!($csvfd = fopen('/tmp'.DS.$csvfile['name'], 'r'))) {
            $message .= ' '.JText::_('COM_JOOMDIET_CSV_CANT_BE_OPENED');
        } else {
            $variables = array();
            $counter = 0;
            $first = true;
            while (($data = fgetcsv($csvfd, 0, ',')) !== false) {
                // TODO: Support for dinamic field ordering.
                if ($first && !is_numeric($data[0]) && (count($data) > 4) &&
                   ($data[0] != '')) {
                    $nut_fields = array();
                    for ($i = 4; $i < count($data); $i++) {
                        $nut_fields[] = $data[$i];
                    }
                } else {
                    $variable = new StdClass();
                    
                    $variable->id = $data[0];
                    $variable->name = $data[1];
                    $variable->description = $data[2];
                    $variable->unit = $data[3];
                    $variable->min_value = $data[4];
                    $variable->max_value = $data[5];
                    $variable->category = $data[6];
                    $variable->nut_relations = array();
                    
                    for ($i = 4; $i < count($data); $i++) {
                        $variable->nut_relations[$nut_fields[$i-4]] = $data[$i];
                    }
                    
                    $variables[] = $variable;
                }
                
                $counter++;
                $first = false;
            }
            
            $this->_import_variables($variables);
        }
        
        $view =& $this->getView('importresults', 'html');
        $view->assignRef('output_messages', $output_messages);
        $view->display();
    }
    
    function processfoodcsv()
    {
        $csvfile = JRequest::getVar('csvfood', null, 'files', 'array');
        $message = "";
        
        if (!is_array($csvfile))
            $message .= JText::_('COM_JOOMDIET_FILE_DOES_NOT_UPLOAD');
        
        if ($csvfile['error'] || ($csvfile['size'] < 1))
            $message .= ' '.JText::_('COM_JOOMDIET_FILE_DOES_NOT_EXIST');
            
        if (!JFile::upload($csvfile['tmp_name'], "/tmp".DS.$csvfile['name'])) {
            $message .= ' '.JText::_('COM_JOOMDIET_UPLOAD_FILE_ERROR');
        }
        
        $output_messages = array();
        $output_messages[] = JText::_('COM_JOOMDIET_CSV_FILE_UPLOADED');
        
        // process csv
        // try to open as csv
        if (!($csvfd = fopen('/tmp'.DS.$csvfile['name'], 'r'))) {
            $message .= ' '.JText::_('COM_JOOMDIET_CSV_CANT_BE_OPENED');
        } else {
            $foodlist = array();
            $counter = 0;
            $first = true;
            while (($data = fgetcsv($csvfd, 0, ',')) !== false) {
                // TODO: Support for dinamic field ordering.
                if ($first && !is_numeric($data[0]) && (count($data) > 4) &&
                ($data[0] != '')) {
                    $var_fields = array();
                    for ($i = 4; $i < count($data); $i++) {
                        $var_fields[] = $data[$i];
                    }
                } else {
                    $food = new StdClass();
                    
                    $food->id = $data[0];
                    $food->name = $data[1];
                    $food->description = $data[2];
                    $food->food_category_id = $data[3];
                    
                    if (count($data) > 4) {
                        $food->var_relations = array();
                        for ($i = 4; $i < count($data); $i++) {
                            $food->var_relations[$var_fields[$i-4]] = $data[$i];
                        }
                    }
                    
                    $foodlist[] = $food;
                    $counter++;
                }
                $first = false;    
            }
            
            $this->_import_food($foodlist);
        }
        
        $view =& $this->getView('importresults', 'html');
        $view->assignRef('output_messages', $output_messages);
        $view->display();
    }
    
    function processreccsv()
    {
        $csvfile = JRequest::getVar('csvrecipes', null, 'files', 'array');
        
        if (!is_array($csvfile))
            $message .= JText::_('COM_JOOMDIET_FILE_DOES_NOT_UPLOAD');
        
        if ($csvfile['error'] || ($csvfile['size'] < 1))
            $message .= ' '.JText::_('COM_JOOMDIET_FILE_DOES_NOT_EXIST');
            
        if (!JFile::upload($csvfile['tmp_name'], "/tmp".DS.$csvfile['name'])) {
            $message .= ' '.JText::_('COM_JOOMDIET_UPLOAD_FILE_ERROR');
        }
        
        $output_messages = array();
        $output_messages[] = JText::_('COM_JOOMDIET_CSV_FILE_UPLOADED');
        
        // process csv
        // try to open as csv
        if (!($csvfd = fopen('/tmp'.DS.$csvfile['name'], 'r'))) {
            $message .= ' '.JText::_('COM_JOOMDIET_CSV_CANT_BE_OPENED');
        } else {
            $recipelist = array();
            $counter = 0;
            $first = true;
            while (($data = fgetcsv($csvfile, 0, '')) !== false) {
                if ($first && !is_numeric($data[0]) && count($data) > 7 &&
                    ($data[0] != '')) {
                        $rec_fields = array();
                        for ($i = 4; $i < count($data); $i++) {
                            $rec_fields[] = $data[$i];
                        }
                } else {
                    $recipe = new StdClass();
                    
                    $recipe->id = $data[0];
                    $recipe->name = $data[1];
                    $recipe->description = $data[2];
                    $recipe->recipe_category_id = $data[3];
                    
                    $recipe->food_rels = array();
                    if (count($data) > 4) {
                        for ($i = 4; $i < count($data); $i++) {
                            $recipe->sug_rels[$var_fields[$i-4]] = $data[$i];
                        }
                    }
                    
                    $recipelist[] = $recipe;
                    $counter++;
                }
                
                $first = false;
            }
            
            $this->_import_recipe($recipelist);
        }
        
        $view =& $this->getView('importresults', 'html');
        $view->assignRef('output_messages', $output_messages);
        $view->display();
    }
    
    function _import_variables($variables)
    {
        $variables_model = $this->getModel('variable');
        
        foreach ($variables as $variable) {
            if ($variable->id && $variables_model->exists($variable->id)) {
                $variables_model->update($variable);
            } else $variables_model->add($variable);
        }
    }
    
    function _import_food($foodlist)
    {
        $food_model = $this->getModel('food');
        
        foreach ($foodlist as $food) {
            if ($food->id && $food_model->exists($food->id)) {
                $food_model->update($food);
            } else $food_model->add($food);
        }
    }
    
    function _import_recipes($recipelist)
    {
        $recipe_model = $this->getModel('recipe');
        
        foreach ($recipelist as $recipe) {
            if ($recipe->id && $recipe_model->exists($recipe->id)) {
                $recipe_model->update($recipe);
            } else $recipe_model->add($recipe);
        }
    }
    
    function generate_food_example()
    {
        $advanced = JRequest::getVar('advanced');
        $food_model = $this->getModel('food');
        
        $example_data = $food_model->getExampleData();
        
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename=file.csv');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        // define headers
        print "id,name,description,food_category_id";
        if ($advanced) {
            $variable_model = $this->getModel('variable');
            $var_names = $variable_model->getNames();
            foreach ($var_names as $name) {
                print ','.$name;
            }
        }
        print "\n";
        
        
        foreach ($example_data as $entry) {
            print $entry->id.','.$entry->name.','.$entry->description.','.$entry->food_category_id;
            if ($advanced) {
                foreach ($var_names as $name) {
                    if (array_key_exists($name, $entry->var_relations))
                        print ','.$entry->var_relations[$name];
                    else print ',';
                }
            }
            print "\n";
        }
    }
    
    function generate_variables_example()
    {
        $variables_model = $this->getModel('variable');
        $example_data = $variables_model->getExampleData();
        
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename=file.csv');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        // define headers
        print "id,name,description,unit,min_value,max_value,category\n";
        
        foreach ($example_data as $entry) {
            print $entry->id.','.$entry->name.','.$entry->description.',';
            print $entry->unit.','.$entry->min_value.','.$entry->max_value.',';
            print $entry->category."\n";
        }
    }
    
    function generate_recipes_example()
    {
        $recipes_model = $this->getModel('recipe');
        $example_data = $recipes_model->getExampleData();
        
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename=file.csv');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        print "id,name,description,recipe_category_id,23,50,21\n";
        print "'','prueba','',0,'23 g','12 Kg','100 mg'";
        print "2,'testing','description',1,'15 mg','100 Kg','100 g'";
        print "\n";
    }
}
?>
